import React, {useState} from 'react';
import {Form, Input, Select, Radio, Modal} from 'acud';

const FormItem = Form.Item;

const areas = [
    {label: 'Beijing', value: 'Beijing'},
    {label: 'Shanghai', value: 'Shanghai'},
];

const UpdateEdit: React.FC<any> = (props) => {
    const {visible, onCancel} = props;
    const [form] = Form.useForm();
    const [type, setType] = useState('WKT');
    const [count, setCount] = useState(0);

    const handleChange = (e: any) => {
        form.resetFields();
        form.setFieldValue('type', e.target.value);
        setType(e.target.value);
        setCount(1);
    };

    const ValidatorForm = (
        <Form form={form} name="dynamic_form_nest_item" labelWidth={60} labelAlign="left" autoComplete="off">
            <FormItem name="type" initialValue={type}>
                <Radio.Group onChange={handleChange}>
                    <Radio value="WKT">单域-wkt</Radio>
                    <Radio value="POINT_2D">多域-点数据</Radio>
                </Radio.Group>
            </FormItem>
            <FormItem name="POINT" label="POINT" extra="POINT (30 10)">
                <Input />
            </FormItem>
            <FormItem name="POLYGON" label="POLYGON" extra="POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))">
                <Input />
            </FormItem>
        </Form>
    );

    const inputItem = (value: any) => (
        <FormItem>
            <p>{count && value}</p>
        </FormItem>
    );

    const oldForm = (
        <Form form={form} name="dynamic_form_nest_item" autoComplete="off">
            <FormItem name="type" initialValue={type}>
                <Radio.Group onChange={handleChange}>
                    <Radio value="WKT">单域-wkt</Radio>
                    <Radio value="POINT_2D">多域-点数据</Radio>
                </Radio.Group>
            </FormItem>
            <FormItem shouldUpdate>
                {({getFieldValue}) => {
                    return (
                        <>
                            <FormItem name="area" label="Area" rules={[{required: true, message: 'Missing area'}]}>
                                <Select options={areas} />
                            </FormItem>
                            {inputItem(getFieldValue('area'))}
                        </>
                    );
                }}
            </FormItem>
        </Form>
    );

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            console.log('---values->', values);
            onCancel();
            form.resetFields();
        }
        catch (error) {}
    };

    return (
        <Modal
            title="表单编辑"
            visible={visible}
            destroyOnClose
            onCancel={onCancel}
            onOk={handleOk}
        >
            {type === 'WKT' ? ValidatorForm : oldForm}
        </Modal>
    );
};

export default UpdateEdit;
